package com.quan.mall.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.quan.common.base.bean.ResultBean;
import com.quan.common.base.constant.CommonConstant;
import com.quan.common.core.BaseService;
import com.quan.common.tools.sms.aliyun.SmsService;
import com.quan.common.utils.RandomUitl;
import com.quan.common.utils.RedisOperator;
import com.quan.mall.entity.MallUser;
import com.quan.mall.service.MallUserService;

import tk.mybatis.mapper.entity.Condition;

/**
 * <p>
 * 电商-会员表 服务实现类
 * </p>
 *
 * @author 杨浩泉
 * @since 2018-11-20
 */
@Service
public class MallUserServiceImpl extends BaseService<MallUser> implements MallUserService {
	
	@Autowired
	private RedisOperator redisOperator;
	
	@Autowired
	private SmsService smsService;
	
	@Override
	public MallUser findByOpenId(String openid) {
		Condition condition = new Condition(MallUser.class) ;
		condition.createCriteria().andEqualTo("openid", openid) ;
		
		return super.selectOne(condition) ;
	}

	@Override
	public MallUser findByMobile(String mobile) {
		Condition condition = new Condition(MallUser.class) ;
		condition.createCriteria().andEqualTo("mobile", mobile) ;
		
		return super.selectOne(condition) ;
	}

	@Override
	public ResultBean sendSMSValidCode(String mobile) {
		try {
			if(StringUtils.isNotBlank(mobile)) {
				String smsCode = RandomUitl.generateInteger(4) ;
				this.smsService.sendSmsMessage(mobile, "杨浩泉", CommonConstant.SMS_TEMPLATE, "{\"code\":\""+smsCode+"\"}") ;
				this.redisOperator.set(CommonConstant.REDIS_KEY_SMS_CODE + mobile, smsCode, 60*30);
			} else {
				return ResultBean.failure("手机号不能为空");
			}
		} catch (Exception e) {
			return ResultBean.failure("短信发送失败，"+e.getMessage());
		}
		
		return ResultBean.ok();
	}

	@Override
	public ResultBean checkSMSValidCode(String mobile, String smsCode) {
		if(StringUtils.isNotBlank(mobile) && StringUtils.isNotBlank(smsCode)) {
			String code = this.redisOperator.get(CommonConstant.REDIS_KEY_SMS_CODE + mobile);
			if(null != code) {
				if(!smsCode.equals(code)) {
					return ResultBean.failure("验证码不正确");
				}
			} else {
				return ResultBean.failure("验证码已过期");
			}
			
		} else {
			return ResultBean.failure("手机号或验证码不能为空");
		}
		
		this.redisOperator.del(CommonConstant.REDIS_KEY_SMS_CODE + mobile);
		return ResultBean.ok();
	}
	
}